// 封装ajax请求
import axios from "axios";
import qs from "qs";
import Vue from "vue";
import { Toast } from "vant";
import {
  getCookie,
  clearAllCookie,
  getStorage,
  removeStorage,
} from "@/utils/common";
import router from "@/router";
Vue.use(Toast);
//测试服
// axios.defaults.baseURL = "http://193.134.208.251:9002";
//正式服
// axios.defaults.baseURL='https://fundapi.fundvaccine.in'

// axios.defaults.baseURL="/"
axios.defaults.timeout = 6000;

// axios取消请求方法
const CancelToken = axios.CancelToken;
let sources = []; // 定义数组用于存储每个ajax请求的取消函数及对应标识
// 定义取消操作
let removeSource = (config) => {
  for (let source in sources) {
    // 当多次请求相同时，取消之前的请求
    if (sources[source].umet === config.url + "&" + config.method) {
      sources[source].cancel("Cancel the request");
      sources.splice(source, 1); ``
    }
  }
};
//请求方式封装
export default function ajax(url = "", data = {}, type = "GET") {
  return new Promise(function (resolve, reject) {
    let promise;
    if (type === "GET") {
      //data: {username: tom, password: 123}
      let paramStr = "";
      Object.keys(data).forEach((key) => {
        paramStr += key + "=" + data[key] + "&";
      });
      if (paramStr) {
        paramStr = paramStr.substring(0, paramStr.length - 1);
        url = url + "?" + paramStr;
      }
      //发送get请求
      promise = axios.get(url);
    } else if (type === "QUERY") {
      // url/params
      url = url + `/${data.id}`;
      promise = axios.get(url);
    } else if (type === "QUERYS") {
      url = url + `/${data.id}`;
      let paramStr = "";
      Object.keys(data).forEach((key) => {
        paramStr += key + "=" + data[key] + "&";
      });
      if (paramStr) {
        paramStr = paramStr.substring(0, paramStr.length - 1);
        url = url + "?" + paramStr;
      }
      console.log(url);
      //发送get请求
      promise = axios.get(url);
    } else if (type == "IMAGE") {
      promise = axios.post(url, data, {
        headers: { "Content-Type": "multipart/form-data" },
      });
    } else if (type == "PATCH") {
      url = url + `/${data.id}`;
      promise = axios.patch(url);
    } else if (type == "PATCHS") {
      promise = axios.patch(url, data);
    } else if (type == "PATCHSSS") {
      url = url + `/${data.id}`;
      promise = axios.patch(url, { type: data.type });
    } else if (type == "DELETE") {
      url = url + `/${data.id}`;
      promise = axios.delete(url);
    } else {
      //发送post请求,qs.stringify将数据转成form格式
      promise = axios.post(url, qs.stringify(data));
    }
    promise
      .then(function (response) {
        resolve(response.data);
      })
      .catch(function (error) {
        reject(error);
      });
  });
}

// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    if (getStorage("token")) {
      // config.headers.Authorization ="Bearer " + getCookie('token')
      config.headers.Authorization = "Bearer " + getStorage("token");
      // config.headers.userid = getCookie('userid')
    }
    //取消相同重复请求
    removeSource(config);
    config.cancelToken = new CancelToken((c) => {
      // 将取消函数存起来
      sources.push({ umet: config.url + "&" + config.method, cancel: c });
    });
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    // 请求结束后将对应存储的取消函数删除
    if (response.data.code == 401) {

      Toast(response.data.msg);
      // localStorage.clear()
      removeStorage("token");
      removeStorage("infpo");
      router.push("/login");
    }
    return Promise.resolve(response);
  },
  function (error) {
    // 对响应错误做点什么

    if (error && error.response) {

      const er = error.response.data.msg || error.response.data.message
      Toast(er);
    }

    return Promise.reject(error);
  }
);
